/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.ai.biz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.controller.LogicRepositoryCrudController;
import org.elsfs.cloud.common.core.vo.R;
import org.elsfs.cloud.common.mybatis.ext.mybatis.extension.LambdaJoinQueryWrapper;
import org.elsfs.cloud.common.mybatis.utils.DateQuery;
import org.elsfs.cloud.common.util.lang.StringUtils;
import org.elsfs.cloud.module.ai.api.entity.AiKnowledge;
import org.elsfs.cloud.module.ai.api.entity.AiModelConfig;
import org.elsfs.cloud.module.ai.biz.repository.AiKnowledgeRepository;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * AI知识库
 *
 * @author zeng
 * @version V1.0.0-M2
 * @since 2025-06-20
 */
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@RestController
@RequestMapping("/aiKnowledge")
@RequiredArgsConstructor
@Tag(description = "aiKnowledge", name = "模型配置管理")
public class AiKnowledgeController
    extends LogicRepositoryCrudController<
        AiKnowledge, AiKnowledge, AiKnowledge, AiKnowledge, AiKnowledgeRepository, String> {
  @Override
  public R<IPage<?>> page(AiKnowledge entity, DateQuery<AiKnowledge> qry) {
    if (!getConfig().page()) {
      return R.error("不支持分页查询");
    }
    final LambdaJoinQueryWrapper<AiKnowledge> queryWrapper =
        new LambdaJoinQueryWrapper<>(AiKnowledge.class)
            .select(true, AiKnowledge::getKnowledgeId, AiKnowledge::getName)
            .select(AiKnowledge.class, j -> true)
            .selectOther(true, AiModelConfig::getModelName)
            .leftJoin(AiModelConfig.class)
            .on()
            .eq(AiKnowledge.Fields.modelId, AiModelConfig.Fields.modelId)
            .end()
            .like(StringUtils.isNotBlank(entity.getName()), AiKnowledge::getName, entity.getName());
    return R.success(repository.joinPage(qry.toPage(), queryWrapper));
  }
}
